package per.turtle.flowable.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.flowable.domain.dto.FlowSaveXmlVo;
import per.turtle.flowable.service.IFlowDefinitionService;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * <p>
 * 工作流程定义
 * </p>
 *
 * @author XuanXuan
 */
@Slf4j
@Tag(name = "流程定义")
@RestController
@RequestMapping("/flowable/definition")
@RequiredArgsConstructor
public class FlowDefinitionController {

    private final IFlowDefinitionService flowDefinitionService;

    @Operation(summary = "删除流程")
    @DeleteMapping(value = "/delete")
    public CommonResult<Void> delete(@Parameter(name = "流程部署ID", required = true) @RequestParam String deployId) {
        flowDefinitionService.delete(deployId);
        return CommonResult.success();
    }

    @Operation(summary = "导入流程文件", description = "上传bpmn20的xml文件")
    @PostMapping("/import")
    public CommonResult<Void> importFile(@RequestParam(required = false) String name, @RequestParam(required = false) String category, MultipartFile file) {
        InputStream in = null;
        try {
            in = file.getInputStream();
            flowDefinitionService.importFile(name, category, in);
        } catch (Exception e) {
            log.error("导入失败:", e);
            return CommonResult.success(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭输入流出错", e);
            }
        }

        return CommonResult.success("导入成功");
    }

    @GetMapping(value = "/list")
    @Operation(summary = "流程定义列表")
    public CommonResult list(@Parameter(name = "当前页码", required = true) @RequestParam Integer pageNum,
                             @Parameter(name = "每页条数", required = true) @RequestParam Integer pageSize,
                             @Parameter(name = "流程名称") @RequestParam(required = false) String name) {
        return CommonResult.success(flowDefinitionService.list(name, pageNum, pageSize));
    }

    @Operation(summary = "读取图片文件")
    @GetMapping("/readImage/{deployId}")
    public void readImage(@Parameter(name = "流程定义id") @PathVariable(value = "deployId") String deployId, HttpServletResponse response) {
        OutputStream os = null;
        BufferedImage image = null;
        try {
            image = ImageIO.read(flowDefinitionService.readImage(deployId));
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Operation(summary = "读取xml文件")
    @GetMapping("/readXml/{deployId}")
    public CommonResult<String> readXml(@Parameter(name = "流程定义id") @PathVariable(value = "deployId") String deployId) {
        try {
            return flowDefinitionService.readXml(deployId);
        } catch (Exception e) {
            return CommonResult.error("加载xml文件异常");
        }

    }

    @Operation(summary = "保存流程设计器内的xml文件")
    @PostMapping("/save")
    public CommonResult<Void> save(@RequestBody FlowSaveXmlVo vo) {
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(vo.getXml().getBytes(StandardCharsets.UTF_8));
            flowDefinitionService.importFile(vo.getName(), vo.getCategory(), in);
        } catch (Exception e) {
            log.error("导入失败:", e);
            return CommonResult.success(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭输入流出错", e);
            }
        }

        return CommonResult.success("导入成功");
    }

    @Operation(summary = "根据流程定义id启动流程实例")
    @PostMapping("/start/{procDefId}")
    public CommonResult start(@Parameter(name = "流程定义id") @PathVariable(value = "procDefId") String procDefId,
                              @Parameter(name = "变量集合,json对象") @RequestBody Map<String, Object> variables) {
        return flowDefinitionService.startProcessInstanceById(procDefId, variables);

    }

    @Operation(summary = "激活或挂起流程定义")
    @PutMapping(value = "/updateState")
    public CommonResult updateState(@Parameter(name = "1:激活,2:挂起", required = true) @RequestParam Integer state,
                                    @Parameter(name = "流程部署ID", required = true) @RequestParam String deployId) {
        flowDefinitionService.updateState(state, deployId);
        return CommonResult.success();
    }

}